package com.fansea.service.serviceIml;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.fansea.entity.Sender;
import com.fansea.service.QqRobotService;
import com.fansea.util.HttpRequestUtil;
import com.fansea.util.TranslateUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Service
@Slf4j
public class QqRobotServiceImpl implements QqRobotService {

    //Ai回复功能
    @Override
    public void QqRobotEvenHandle(HttpServletRequest request) {
        //JSONObject
        JSONObject jsonParam = this.getJSONParam(request);
        String senderStr = jsonParam.getString("sender");
        Sender sender = JSONUtil.toBean(senderStr, Sender.class);
        Long userId = null;
        Long groupId = null;
        String result = null;
        log.info("接收参数为:{}", jsonParam.toString() != null ? "SUCCESS" : "FALSE");
        if ("message".equals(jsonParam.getString("post_type"))) {
            String message = jsonParam.getString("message");
//            String translate = AiChatUtil.AiRecovery(message);
            String translate = TranslateUtil.translate(message);
            translate = URLEncoder.encode(translate,StandardCharsets.UTF_8);
            if("private".equals(jsonParam.getString("message_type"))){
                userId = sender.getUserId();
                // user_id 为QQ好友QQ号
                String url = "http://127.0.0.1:5700/send_private_msg?user_id=" + userId + "&message=" + translate;
                result = HttpRequestUtil.doGet(url);
            }else if ("group".equals(jsonParam.getString("message_type"))){
                groupId = Long.valueOf(jsonParam.getString("group_id"));
                System.out.println("groupId:"+groupId);
                String url = "http://127.0.0.1:5700/send_group_msg?group_id=" + groupId + "&message=" + translate;
                result = HttpRequestUtil.doGet(url);
            }
            log.info("发送成功:==>{}", result);
        }
    }

    public JSONObject getJSONParam(HttpServletRequest request) {
        JSONObject jsonParam = null;
        try {
            // 获取输入流
            BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
            // 数据写入Stringbuilder
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = streamReader.readLine()) != null) {
                sb.append(line);
            }
            jsonParam = JSONObject.parseObject(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonParam;
    }


}
